package com.app.util.common;


import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringUtil {

	public static <T> T getBean(Class<T> c) {
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(getContext()); 
	    return ac.getBean(c);
	}
	/**
	 * 根据bean名称获取bean 
	 * @param name
	 * @param context
	 * @return
	 */
	public static Object getBean(String name,ServletContext context) {
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context); 
	    return ac.getBean(name);
	}
	
	
	/**
	 * 根据bean类型获取
	 * @param c
	 * @param context
	 * @return
	 */
	public static <T> T getBean(Class<T> c,ServletContext context) {
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context); 
	    return ac.getBean(c);
	}
	
	public static ServletContext getContext() {
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
		ServletContext servletContext = webApplicationContext.getServletContext();
		return servletContext;
	}
}
